package com.jiaquyun.jcyx.main.goods

import android.graphics.Typeface
import android.os.Bundle
import android.view.Gravity
import android.view.View
import android.widget.FrameLayout
import android.widget.LinearLayout
import android.widget.TextView
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.ColorUtils
import com.blankj.utilcode.util.ConvertUtils
import com.jiaquyun.jcyx.R
import com.jiaquyun.jcyx.entity.*
import com.jiaquyun.jcyx.main.goods.adapter.CateTwoAdapter
import com.jiaquyun.jcyx.main.goods.adapter.GoodsListAdapter
import com.jiaquyun.jcyx.jetpack.mode.GoodsViewModel
import com.module.lemlin.custom.SpacingItemDecoration
import com.module.lemlin.http.Status
import com.module.lemlin.http.msg
import com.module.lemlin.image.loadRoundImage
import com.module.lemlin.owner.OwnerViewModeFragment
import kotlinx.android.synthetic.main.fragment_goods_screen.*
import kotlinx.android.synthetic.main.include_goods_screen.*

class GoodsScreenFragment : OwnerViewModeFragment<GoodsViewModel>() {

    companion object {
        private const val EXTRA_NAME_CATE = "EXTRA_NAME_CATE"
        private const val EXTRA_NAME_SEARCH = "EXTRA_NAME_CATE"
        fun newInstance(cateEntity: Cat?): GoodsScreenFragment {
            val bundle: Bundle = Bundle().apply {
                putSerializable(EXTRA_NAME_CATE, cateEntity)
            }
            return GoodsScreenFragment().apply {
                arguments = bundle
            }
        }

        fun newInstance(search: String?): GoodsScreenFragment {
            val bundle: Bundle = Bundle().apply {
                putString(EXTRA_NAME_SEARCH, search)
            }
            return GoodsScreenFragment().apply {
                arguments = bundle
            }
        }
    }

    private val cateTwoAdapter: CateTwoAdapter = CateTwoAdapter()
    private val goodsListAdapter: GoodsListAdapter = GoodsListAdapter()

    private var mCateEntity: Cat? = null
    private var mSearch: String? = null

    override val layoutResId: Int
        get() = R.layout.fragment_goods_screen

    override fun viewModel(): GoodsViewModel {
        return createViewModel()
    }

    override fun initView() {

        mCateEntity = arguments?.getSerializable(EXTRA_NAME_CATE) as? Cat
        mSearch = arguments?.getString(EXTRA_NAME_SEARCH)

        mCateEntity?.let {
            ivGoodsCateIcon.loadRoundImage(it.image, radius = ConvertUtils.dp2px(5f))
        }

        //初始化分类标签视图
        rvGoodsScreenLabel.apply {
            layoutManager = LinearLayoutManager(requireContext()).apply {
                orientation = LinearLayoutManager.HORIZONTAL
            }
        }.adapter = cateTwoAdapter.apply {
            mCateEntity?.let {
                val cateEntity = Cat(
                    id = it.id, image = it.image, level = it.level, name = "全部", pid = it.pid
                )
                setNewInstance(mutableListOf(cateEntity))
            }
        }
        cateTwoAdapter.setOnItemClickListener { _, _, position ->
            cateTwoAdapter.selectedPosition = position
            val cateEntity: Cat = cateTwoAdapter.getItem(position)
            fillGoodsListSort(viewModel.mGoodsRequest.apply { cat_id = cateEntity.id })
        }

        //初始化物品列表视图
        rvGoodsScreenBody.apply {
            val decoration = SpacingItemDecoration(
                vGap = ConvertUtils.dp2px(10f),
                hGap = ConvertUtils.dp2px(10f)
            )
            addItemDecoration(decoration)
            itemAnimator?.changeDuration = 0
        }.adapter = goodsListAdapter.apply {
            if (mCateEntity != null || mSearch != null) {
                setEmptyView(createLoadingView())
            }
        }
        goodsListAdapter.setOnItemChildClickListener { _, view, position ->
            val itemData: GoodsGroup = goodsListAdapter.getItem(position)
            if (view.id == R.id.ivGoodsPlus) {
                val num: Int = itemData.cart_num + 1
                if (itemData.cart_id == 0 || itemData.cart_num == 0) {
                    viewModel.cartAdd1(itemData.id, num)
                } else {
                    viewModel.cartChangeNum1(itemData.id, itemData.cart_id, num)
                }
            }
            if (view.id == R.id.ivGoodsMinus) {
                val num: Int = itemData.cart_num - 1
                if (num == 0) {
                    viewModel.cartRemove(itemData.id, itemData.cart_id)
                } else {
                    viewModel.cartChangeNum1(itemData.id, itemData.cart_id, num)
                }
            }
        }

        //综合排序
        llGoodsScreenSortComplex.setOnClickListener {
            fillGoodsListSort(viewModel.mGoodsRequest.apply {
                sort_asc = if (sort_asc == null)
                    0 else if (sort != null)
                    0 else if (sort_asc == 0)
                    1 else null
                sort = null
            })
        }

        //价格排序
        llGoodsScreenSortPrice.setOnClickListener {
            fillGoodsListSort(viewModel.mGoodsRequest.apply {
                sort_asc = if (sort == null || sort_asc == null)
                    0 else if (sort != "price")
                    0 else if (sort_asc == 0)
                    1 else null
                sort = if (sort_asc == null) null else "price"
            })
        }

        //销量排序
        llGoodsScreenSortCount.setOnClickListener {
            fillGoodsListSort(viewModel.mGoodsRequest.apply {
                sort_asc = if (sort == null || sort_asc == null)
                    0 else if (sort != "sales_sum")
                    0 else if (sort_asc == 0)
                    1 else null
                sort = if (sort_asc == null) null else "sales_sum"
            })
        }

        mSmartRefreshLayout.setEnableRefresh(false)
        mSmartRefreshLayout.setEnableLoadMore(false)
        mSmartRefreshLayout.setOnLoadMoreListener {
            viewModel.goodsList(isLoadMore = true)
        }
    }

    override fun initData() {
        mCateEntity?.let {
            viewModel.goodsCategoryList(it.id)
            fillGoodsListSort(viewModel.mGoodsRequest.apply { cat_id = it.id })
        }

        mSearch?.let {
            fillGoodsListSort(viewModel.mGoodsRequest.apply { this.search = it })
        }

//        viewModel.cartIndex()
    }

    override fun initViewMode() {

        viewModel.searchLiveData.observe(viewLifecycleOwner, Observer { search ->
            search?.let {
                fillGoodsListSort(viewModel.mGoodsRequest.apply { this.search = it })
            }
        })

        viewModel.cateListLiveData.observe(viewLifecycleOwner, Observer { response ->
            if (response.status == Status.SUCCESS) {
                response.data?.data?.let {
                    cateTwoAdapter.addData(it)
                }
            }
        })

        viewModel.goodsListLiveData.observe(viewLifecycleOwner, Observer { response ->
            if (response.status == Status.FAILURE) {
                toast(response.error?.msg ?: "位置错误")
                mSmartRefreshLayout.finishLoadMore((false))
            } else if (response.status == Status.SUCCESS) {
                mSmartRefreshLayout.finishLoadMore()
            }
            if (response.status != Status.SUCCESS)
                return@Observer
            response.data?.let {
                if (it.data.size == 0) {
                    goodsListAdapter.setEmptyView(createEmptyView())
                }
                if (it.loadMore) {
                    goodsListAdapter.addData(it.data)
                } else {
                    goodsListAdapter.setNewInstance(it.data)
                }
                if (it.data.size < viewModel.mGoodsRequest.rows) {
                    goodsListAdapter.setFooterView(createFooterView())
                    mSmartRefreshLayout.setEnableLoadMore(false)
                } else {
                    goodsListAdapter.removeAllFooterView()
                    mSmartRefreshLayout.setEnableLoadMore(true)
                }
            }
        })

        //监听购物车添加
        viewModel.cartAdd1LiveData.observe(viewLifecycleOwner, Observer { response ->
            if (response.status == Status.FAILURE) {
                toast(response.error?.msg)
            }
        })

        //监听购物车加减
        viewModel.cartChangeNum1LiveData.observe(viewLifecycleOwner, Observer { response ->
            if (response.status == Status.FAILURE) {
                toast(response.error?.msg)
            }
        })

        //监听购物车删除
        viewModel.cartDelete1LiveData.observe(viewLifecycleOwner, Observer { response ->
            if (response.status == Status.FAILURE) {
                toast(response.status.desc)
            }
        })
    }

    override fun onEventMainThread(any: Any) {
        if (any !is CartAction)
            return
        if (any.action == CartAction.Action.CLEAR) {
            val position = mutableListOf<Int>()
            for ((index, item) in goodsListAdapter.data.withIndex()) {
                if (item.cart_num != 0) position.add(index)
            }
            position.forEach {
                goodsListAdapter.setData(it)
            }
        } else {
            val position = goodsListAdapter.data.indexOfFirst {
                it.id == any.goodsId
            }
            if (position == -1)
                return
            goodsListAdapter.setData(position, any.goodsNum, any.cartId)
        }
    }


    private fun fillGoodsListSort(goodsRequest: GoodsRequest) {

        val drawable: Int = when (goodsRequest.sort_asc) {
            0 -> R.drawable.ic_14343
            1 -> R.drawable.ic_14344
            else -> R.drawable.ic_14342
        }

        ivGoodsScreenSortComplex.setImageResource(
            if (goodsRequest.sort == null) drawable else R.drawable.ic_14342
        )

        ivGoodsScreenSortPrice.setImageResource(
            if (goodsRequest.sort == "price") drawable else R.drawable.ic_14342
        )
        ivGoodsScreenSortCount.setImageResource(
            if (goodsRequest.sort == "sales_sum") drawable else R.drawable.ic_14342
        )

        viewModel.goodsList()
    }

    private fun createLoadingView(): View {
        return layoutInflater.inflate(R.layout.dialog_load_style_2, null)
    }

    private fun createEmptyView(): View {
        return layoutInflater.inflate(R.layout.view_empty_error, null)
    }

    private fun createFooterView(): View = TextView(requireContext()).apply {
        layoutParams = FrameLayout.LayoutParams(
            LinearLayout.LayoutParams.MATCH_PARENT,
            ConvertUtils.dp2px(30f)
        )
        gravity = Gravity.CENTER
        textSize = 13f
        text = "没有更多商品"
        setTypeface(null, Typeface.BOLD)
        setTextColor(ColorUtils.getColor(R.color.FF_666666))
    }

//    private fun createHeadsView(): View = RecyclerView(requireContext()).apply {
//
//        layoutParams = FrameLayout.LayoutParams(
//            LinearLayout.LayoutParams.MATCH_PARENT,
//            LinearLayout.LayoutParams.WRAP_CONTENT
//        ).apply {
//            setMargins(0, ConvertUtils.dp2px(10f), 0, 0)
////            setPadding(ConvertUtils.dp2px(5f), 0, ConvertUtils.dp2px(5f), 0)
//        }
//        layoutManager = LinearLayoutManager(requireContext()).apply {
//            orientation = LinearLayoutManager.HORIZONTAL
//        }
//        adapter = cateTwoAdapter.apply {
//            mCateEntity?.let {
//                val cateEntity = Cat(
//                    id = it.id, image = it.image, level = it.level, name = "全部", pid = it.pid
//                )
//                setNewInstance(mutableListOf(cateEntity))
//            }
//        }
//    }

}